<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/


/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAJobs extends JModel {
	var $_table;
	var $_pagination;
	var $_fieldList = null;
	var $_searchparams;
	var $_fieldListEdit;
	var $_table_name = 'ja_jobs';
	
	function download(){
        $cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
        $table =& $this->_getTable(); 
		$table->_tbl_key = 'id';
        $table->load($cid[0]);
        
        $file_attachment 		= JRequest::getVar("field_name", "");
        $table->file_attachment = $table->{$file_attachment};        
        $file_name = explode('/',$table->file_attachment);        
        
        if( $table->file_attachment) {
        	$file = JPATH_SITE.DS.str_replace('/','\\',$table->file_attachment);
	        if (file_exists(str_replace('/','\\',$file)))
	        	$file = str_replace('/','\\',$file);
	        else 
        		$file = str_replace('\\','/',$file);
        	
            header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.substr ( $file_name [count ( $file_name ) - 1], 14 ) .'"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean();
		    flush();
		    readfile($file);
        }
    }
	
	/**
	 * Return the query is used to retrive all row from database
	 * @return string The query is used 
	 */
	function getItems($where_more = '', $limit, $limitstart, $order = '', $count=false) {
		global $mainframe, $jbconfig, $option;
		
		// Get the page/component configuration
		$params = &$mainframe->getParams ();
		
		$db = JFactory::getDBO ();
		
		$request = JRequest::get('request');
		
		if(isset($request['cat_id']) && !is_array($request['cat_id']) ){
			$request['cat_id'] = str_replace( "--", "&amp;", $request['cat_id']);
			if( strpos($request['cat_id'], "+") == 0 )
				$request['cat_id'] = trim($request['cat_id']);
		}
		if(isset($request['location_id']) && !is_array($request['location_id']) ){       
			$request['location_id'] = str_replace( "--", "&amp;", $request['location_id']);		
			if( strpos($request['location_id'], "+") == 0 )
				$request['location_id'] = trim($request['location_id']);
		}
		if(isset($request)){  
			$filter_field_keys = array_keys($request);
		}
				
		$search = JRequest::getVar ( 'search', '' );
		$search = trim(JString::strtolower ( $search ));
		
		$user = JFactory::getUser ();
		$this->getFieldList ( ' and fl.admin_only=0 ' );
		$this->getEditFieldList ( ' and f.frontend_hidden=0' );
				
		if (JRequest::getVar ( 'view' ) == 'jajobs')
			$filter_order = JRequest::getVar('filter_order', '', 'cmd');
		else
			$filter_order = '';
		$filter_order_Dir = JRequest::getVar('filter_order_Dir', '', 'word');
		
		// just in case filter_order get's messed up
		$join = '';
		$orderby = '';
		$where = "";
		$fields_show = '';
				
		$join_clause_field = array ();
		$join_clause_table = array ();
		$field_temp = array();
		$subwhere = array ();		
		$where_clause = array();		
				
		
		$join_clause_table['profi'] =  "\n INNER JOIN #__ja_profiles as  profi";
		$join_clause_table['rs'] =  "\n INNER JOIN #__users as rs";
		
		$join_clause_field['profi'] = "  ON profi.user_id=a.user_id and profi.approved=1";
		$join_clause_field['rs'] = " ON rs.id=a.user_id and rs.block=0";
		
		if ( $count === false )
			JB_Build_where($join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, $filter_field_keys, $request, $search);
		else JB_Build_where($join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, '', '', $search);
		
		if ($order) {
			$orderby .= $order;
		}
		if ($filter_order) {			
			if ($orderby)	$orderby .= ',';
			$orderby .= $filter_order . ' ' . $filter_order_Dir ;
		
		} elseif (! $order) {
			$orderby = " a." . $jbconfig ['posts']->get ( 'filter_order' ) . " " . $jbconfig ['posts']->get ( 'filter_order_Dir' );
		}
		
		$posted_date = JRequest::getVar ( 'posted_date' );
		if ($posted_date){
			$where_clause [] = "( DATE_ADD (a.effected_date, INTERVAL " . $posted_date . " DAY )>=now() )";
		}
		
		if($field_temp){
			$fields_show = ', '. implode(', ', $field_temp);	
		}
		
		foreach ($join_clause_table as $j=>$table){
			$join .= "\n $table ";
			if(isset($join_clause_field[$j])){
				$join .= $join_clause_field[$j];
			}
		}
			
		if ($where_clause) {
			$where = ' AND ' .implode(' AND ', $where_clause);
		}
		
		/* Count items */
		$query = "SELECT count(distinct a.id) ".
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more;	
		
		$db->setQuery ( $query );
		$total = $db->loadResult ();
		JRequest::setVar ( 'initial_total', $total );
		jimport ( 'joomla.html.pagination' );
		require_once (JPATH_SITE . DS . 'components' . DS . 'com_jajobboard' . DS . 'helper' . DS . 'japagination.php');
		$this->_pagination = new JAPagination ( $total, $limitstart, $limit );
		
		/* Get all items */
		$query = "SELECT distinct a.id, a.*, profi.company, profi.logo, profi.id as profileid $fields_show" . 
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more.
					"\n ORDER BY ". $orderby . ', a.effected_date desc';
				
		$db->setQuery ( $query, $limitstart, $limit );
		
		$items = $db->loadObjectList ();
		
		$jconfig = new JConfig();
		$timezone = $jconfig->offset;
		
		if ($items) {
			foreach ( $items as $k => $job ) 
				if (isset($job->id)){					
					$job->title = JFilterInput::_decode ( $job->title );
					$job->job_detail = JFilterInput::_decode ( $job->job_detail );								
								
					$enable_timestamp = isset ( $jbconfig ['general'] ) ? $jbconfig ['general']->get ( 'posts_show_published_date', 1 ) : 1;
				
					if ($enable_timestamp && $job->effected_date) {
						$job->effected_date = generatTimeStamp ( strtotime ( $items [$k]->effected_date ) );
						if( isset($job->expiry_date) )
						  $job->expiry_date = generatTimeStamp ( strtotime ( $items [$k]->expiry_date ) );
					} elseif ($job->effected_date) {
						if (! $user)
							$job->effected_date = generateDate ( $items [$k]->effected_date );
						else
							$job->effected_date = generateDate ( date ( 'Y-m-d H:i:s', strtotime ( $items [$k]->effected_date ) - date ( 'Z' ) + $user->getParam ( 'timezone', $timezone ) * 60 * 60 ) );
						
						if( isset($job->expiry_date) ){
						   if (! $user)
							 $job->expiry_date = generateDate ( $items [$k]->expiry_date );
						  else
							 $job->expiry_date = generateDate ( date ( 'Y-m-d H:i:s', strtotime ( $items [$k]->expiry_date ) - date ( 'Z' ) + $user->getParam ( 'timezone', $timezone ) * 60 * 60 ) );
						 
					    }
					}
					
					if ($items [$k]->created_date)
					{
						if (! $user)
							$job->created_date = generateDate ( $items [$k]->created_date );
						else
							$job->created_date = generateDate ( date ( 'Y-m-d H:i:s', strtotime ( $items [$k]->created_date ) - date ( 'Z' ) + $user->getParam ( 'timezone', $timezone ) * 60 * 60 ) );
					}
					
					if ($this->_fieldList) {
						foreach ( $this->_fieldList as $field ) {
							
							$job->{$field->field_name} = JFilterInput::_decode ( $job->{$field->field_name} );
								
							if ($field->field_type == 'TEXTFIELD'){
								$job->{$field->field_name} = JFilterInput::clean ( $job->{$field->field_name} );
							}							

							
							if ($field->is_referred > 0 && $job->{$field->field_name}) {
								
								
								$values = explode(',', $job->{$field->field_name});
								foreach ($values as $i=>$v){
									$values[$i] = $db->Quote($v);	
								}
								$values = implode(',', $values);
								if(!$values) $values = 0;
								$sql = "SELECT {$field->referred_value} ".
										"\n FROM #__{$field->referred_table} ".
										"\n WHERE {$field->referred_key} in ($values)";
								$db->setQuery ( $sql );
								$result = $db->loadResultArray ();
								if ($result) {
									$job->{$field->field_name} = implode(', ', $result);
								}
								else{
									$job->{$field->field_name} = '';
								}
								
								
							} elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) ) && $job->{$field->field_name}) {
								
								$values = explode(',', $job->{$field->field_name});
								foreach ($values as $i=>$v){
									$values[$i] = $db->Quote($v);	
								}
								$values = implode(',', $values);
								$field_id = $field->table_name . '_' . $field->field_name;
								
								$sql = "SELECT text ".
										"\n FROM #__ja_codes ".
										"\n WHERE value in ($values) and field_id='$field_id' ";
																
								$db->setQuery ( $sql );
								$result = $db->loadResultArray ();
								
								if ($result) {
									$job->{$field->field_name} = implode(', ', $result);
								}
								else{
									$job->{$field->field_name} = '';
								}
							}
					}
					
					$items [$k] = $job;
				}
			}
		}
		
		return $items;
	
	}
	
	function getSubId($table_name, $ids) {
		$db = JFactory::getDBO ();
		$arr_id = explode ( ',', $ids );
		$n = count ( $arr_id );
		$orginal_n = $n;
		$db = JFactory::getDBO ();
		for($i = 0; $i < $n; $i ++)
			
			if (isset ( $arr_id [$i] ) && $arr_id [$i] != '') {
				$id = $arr_id [$i];
				$query = "SELECT id FROM #__$table_name WHERE parent_id=" . ( int ) $id;
				$db->setQuery ( $query );
				$result = $db->loadObjectList ();
				if (is_array ( $result ))
					foreach ( $result as $result_id ) {
						$arr_id [] = $result_id->id;
						$n ++;
					}
			
			}
		$n = $orginal_n;
		for($i = 0; $i < $n; $i ++)
			if (isset ( $arr_id [$i] ) && $arr_id [$i] != '') {
				$id = $arr_id [$i];
				$query = "SELECT parent_id FROM #__$table_name WHERE id=" . ( int ) $id;
				$db->setQuery ( $query );
				$result = $db->loadObjectList ();
				if (is_array ( $result ))
					foreach ( $result as $result_id ) {
						if ($result_id->parent_id != 0) {
							$arr_id [] = $result_id->parent_id;
							$n ++;
						}
					}
			}
		$arr_id = array_unique ( $arr_id );
		return implode ( ',', $arr_id );
	
	}
	
	function check_multi_level($table_name) {
		$db = JFactory::getDBO ();
		$query = "SELECT parent_id FROM #__$table_name";
		$db->setQuery ( $query );
		$result = $db->loadObjectList ();
		if ($result != null)
			return true;
		else
			return false;
	}
	function getListId_from_ListName($field) {
		$db = JFactory::getDBO ();
		if (! is_array ( $field->value ))
			$temp = explode ( ',', $field->value );
		else
			$temp = $field->value;
		if (is_array ( $temp ))
			for($i = 0; $i < count ( $temp ); $i ++)
				$temp [$i] = "'" . $temp [$i] . "'";
		$field->value = implode ( ',', $temp );
		if ($field->is_referred) {
			$query = "SELECT $field->referred_key FROM #__$field->referred_table WHERE $field->referred_value IN ($field->value)";
			$db->setQuery ( $query );
			$result = $db->loadObjectList ();
			$temp = array ();
			if (is_array ( $result ))
				for($i = 0; $i < count ( $result ); $i ++) {
					$temp [] = $result [$i]->{$field->referred_key};
				}
			$temp = implode ( ',', $temp );
			if ($this->check_multi_level ( $field->referred_table )) {
				$temp = $this->getSubId ( $field->referred_table, $temp );
			
			}
		} elseif ((trim ( $field->field_type ) == 'SELECT') || (trim ( $field->field_type ) == 'MSELECT')) {
			$query = "SELECT value FROM #__ja_codes WHERE text IN ($field->value)";
			$db->setQuery ( $query );
			$result = $db->loadObjectList ();
			$temp = array ();
			if (is_array ( $result ))
				for($i = 0; $i < count ( $result ); $i ++) {
					$temp [] = $result [$i]->value;
				}
			//    		$temp = implode(',',$temp);	
		}
		return $temp;
	}
	
	/**
	 * @desc Get all fields that will be displayed on edit form
	 */
	function getEditFieldList($where = '') {
		if (! $this->_fieldListEdit) {
			$this->_fieldListEdit = getEditFieldList ( $this->_table_name, $where );
		}
		return $this->_fieldListEdit;
	}
	
	function getFieldList($where = '') {
		if (! $this->_fieldList) {
			$this->_fieldList = getFieldList ( $this->_table_name, $where );
		}
		
		return $this->_fieldList;
	}
	
	/**
	 * Get field table instance
	 * @return JTable Configuration table object
	 */
	function &_getTable() {
		if ($this->_table == null) {
			$this->_table = &JTable::getInstance ( 'JA_Jobs', 'JobBoardTable' );
		}
		
		return $this->_table;
	}
	
	/**
	 * Get page navigator object
	 * @return 
	 */
	function &getPagination() {
		if ($this->_pagination == null) {
			$this->getItems ( '', JRequest::getVar ( 'limit' ), JRequest::getVar ( 'limitstart' ) );
		}
		return $this->_pagination;
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableJA_resumes Table object
	 */
	function getItem() {
		
		$table = & $this->_getTable ();
		// Load the current item if it has been defined
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		
		if ($cid[0]) {
			$table->load ( $cid [0] );
		}
		$user = JFactory::getUser ();
		
		if ($user->id != $table->user_id && isset ( $table->views )) {
			
			if ($table->views == null)
				$table->views = 0;
				//			else 
			//				$table->views = $table->views + 1;
			

			$this->increaseViews ( $table );
		
		}
		if ($user->id != $table->user_id)
			$this->Set_LatestJob_View ( $table );
		$item = $table;
		if (isset ( $_COOKIE ['cookie_filter_keyword'] ))
			$filter_keyword = $_COOKIE ['cookie_filter_keyword'];
		else
			$filter_keyword = false;
		if (isset ( $filter_keyword )) {
			$arr_jobsearch_keyword = standardize_keyword ( $filter_keyword );
		if (JRequest::getVar('layout')!='jaform' && JRequest::getVar('japremiumform'))	
		{
			if (isset ( $item->title ))
				foreach ( $arr_jobsearch_keyword as $k => $value )
					$item->title = str_ireplace ( $value, "<strong class='highlight'>" . $value . "</strong>", $item->title );
			if (isset ( $item->job_detail ))
				foreach ( $arr_jobsearch_keyword as $k => $value )
					$item->job_detail = str_ireplace ( $value, "<strong class='highlight'>" . $value . "</strong>", $item->job_detail );
			setcookie ( 'cookie_filter_keyword', '', time () - 3600 );
		}
		}
		
		return $item;
	}
	
	
	function checkItem($cid){		
		$db = JFactory::getDBO();
		$sql = "SELECT count(*) FROM jos_ja_jobs WHERE id = '$cid'";
		$db->setQuery($sql);
		return $db->loadResult();		
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableJA_Jobs Table object
	 */
	function getProfileFromUserId() {
		$user_id = JRequest::getVar ( 'user_id' );
		$db = JFactory::getDBO ();
		$query = "SELECT p.*" . " FROM #__ja_profiles AS p " . " WHERE p.user_id = " . $user_id;
		
		$db->setQuery ( $query );
		$profile = $db->loadObject ();
		
		return $profile;
	}
	
	function getAppFieldList() {
		require_once JPATH_COMPONENT_SITE . DS . 'models' . DS . 'jaapplications.php';
		$app_model = new JobBoardModelJAApplications ( );
		$appFieldList = $app_model->getEditFieldList ();
		return $appFieldList;
	}
	
	function getAppItem() {
		require_once JPATH_COMPONENT_SITE . DS . 'models' . DS . 'jaapplications.php';
		$app_model = new JobBoardModelJAApplications ( );
		$appItem = $app_model->getAppItem ();
		return $appItem;
	
	}
	
	function getAdminItems() {
		global $mainframe;
		
		$db = JFactory::getDBO ();
		
		$search = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jajobs.search", 'search', '', 'string' );
		$search = JString::strtolower ( $search );
		
		$this->getFieldList ( ' and fl.admin_only=0 ' );
		$this->getAdminEditFieldList ();
		
		$filter_order = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jajobs.filter_order", 'filter_order', '', 'cmd' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest ( JBCOMNAME . ".jajobs.filter_order_Dir", 'filter_order_Dir', 'ASC', 'word' );
		
		$orderby = '';
		// just in case filter_order get's messed up
		if ($filter_order) {
			$orderby = ' ORDER BY ' . $filter_order . ' ' . $filter_order_Dir;
		} else {
			$orderby = ' ORDER BY a.created_date ';
		}
		
		$where = array ();
		
		$num_of_join_tables = 0;
		$num_of_join_tables_1 = 0;
		$field_clause = array ();
		$join_clause = array ();
		
		foreach ( $this->_fieldList as $field ) {
			$field_clause [] = "a." . $field->field_name;
			if ($search) {
				if ($field->is_referred > 0) {
					$alias = chr ( ord ( 'b' ) + $num_of_join_tables_1 );
					$subwhere [] .= " ($alias.$field->referred_value LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
					$num_of_join_tables_1 ++;
				} elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) )) {
					$subwhere [] = "(#__ja_codes.text LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
				} else {
					$subwhere [] .= " (a.$field->field_name LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
				}
				$where [] = '(' . implode ( 'or', $subwhere ) . ')';
			}
		}
		$where_clause = "";
		if (count ( $where )) {
			$where_clause = " WHERE " . implode ( ' and ', $where );
		}
		
		$field_clause [] = "a.id";
		$field_clause [] = "a.checked_out";
		$field_clause [] = "a.checked_out_time";
		
		// Build main query
		if (count ( $field_clause )) {
			// $query = "SELECT ". implode(", ", $field_clause)
			$query = "SELECT *" . " FROM #__$this->_table_name AS a" . (count ( $join_clause ) ? implode ( " ", $join_clause ) : "") . $where_clause . $orderby;
		} else {
			$query = "SELECT * FROM #__$this->_table_name" . $where_clause . $orderby;
		}
		
		$db->setQuery ( $query );
		$items = $db->loadObjectList ();
		
		$filter_list = array ();
		
		if ($items) {
			
			foreach ( $this->_fieldListEdit as $field ) {
				if ($field->is_on_filter) {
					$field->value = $mainframe->getUserStateFromRequest ( $option . ".jajobs." . $field->field_name, $field->field_name, $field->field_init, 'string' );
					if ($field->value != '')
						$filter_list [] = $field;
				}
			}
			
			if ($filter_list) {
				foreach ( $items as $i => $job ) {
					$job = parse_content_item ( $job, $filter_list );
					
					foreach ( $filter_list as $k => $f ) {
						if ($f->value && is_array ( $job->{$f->field_name} ) && ! in_array ( $f->value, $job->{$f->field_name} )) {
							
							unset ( $items [$i] );
							break;
						} elseif ($f->value && ! is_array ( $job->{$f->field_name} ) && $f->value != $job->{$f->field_name}) {
							unset ( $items [$i] );
							break;
						}
					
					}
				
				}
			}
			
			foreach ( $items as $k => $job ) {
				
				foreach ( $this->_fieldList as $field ) {
					if (is_array ( $job->{$field->field_name} ))
						$job->{$field->field_name} = implode ( ',', $job->{$field->field_name} );
					if ($field->is_referred > 0) {
						$value = array ();
						$sql = "select {$field->referred_value} as {$field->field_name} from #__{$field->referred_table} where {$field->referred_key} in ({$job->{$field->field_name}})";
						$db->setQuery ( $sql );
						$result = $db->loadObjectList ();
						if ($result) {
							foreach ( $result as $row ) {
								$value [] = $row->{$field->field_name};
							}
						}
						
						if ($value)
							$value = implode ( ', ', $value );
						else
							$value = '';
						$job->{$field->field_name} = $value;
					} elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) )) {
						$value = array ();
						$sql = "select text from #__ja_codes where value ";
						if (is_array ( $job->{$field->field_name} ))
							$sql .= "in ({$job->{$field->field_name}})";
						else
							$sql .= "= '{$job->{$field->field_name}}'";
						$name = $field->table_name . '_' . $field->field_name;
						$sql .= " and field_id='$name'";
						$db->setQuery ( $sql );
						$result = $db->loadObjectList ();
						
						if ($result) {
							foreach ( $result as $row ) {
								$value [] = $row->text;
							}
						}
						
						if ($value)
							$value = implode ( ', ', $value );
						else
							$value = '';
						$job->{$field->field_name} = $value;
					}
				}
				
				$items [$k] = $job;
			
			}
		}
		$total = count ( $items );
		
		jimport ( 'joomla.html.pagination' );
		$this->_pagination = new JPagination ( $total, $limitstart, $limit );
		
		$list = array ();
		// slice out elements based on limits
		if (is_array ( $items ))
			$list = array_slice ( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
	}
	
	function getAppliedList() {
		$job_id = JRequest::getVar ( 'job_id' );
		$db = &JFactory::getDBO ();
		if ($job_id) {
			$query = "SELECT a.id, a.subject AS title, r.id as resume_id, a.attachment, a.created_date " . " FROM #__ja_applications AS a " . " LEFT JOIN #__ja_resumes as r ON r.user_id=a.user_id " . " WHERE a.job_id = " . ( int ) $job_id . " ORDER BY a.ccreated_date DESC";
			
			$db->setQuery ( $query );
			
			$applied = $db->loadObjectList ();
			return $applied;
		}
		return null;
	}
	
	function getHotJobOptions() {
		$db = &JFactory::getDBO ();
		$query = "SELECT id, ckeytitle, ckey, cvalue FROM #__ja_config WHERE ckey LIKE 'HOTJOB%' ORDER BY ckey";
		$db->setQuery ( $query );
		$cfg = $db->loadObjectList ();
		return $cfg;
	}
	
	/** 
	 * Store configuration item
	 * @param array The post array
	 */
	function store() {
		global $jbconfig;
		
		$controller = JRequest::getVar ( 'view' );
		$step = JRequest::getVar ( 'step', '' );
		$db = & JFactory::getDBO ();
		$row = & $this->getItem ();
		$old_job_type = $row->job_type;
		$old_title = $row->title;
		$old_job_detail = $row->job_detail;
		$old_cat_id = $row->cat_id;
		$old_location_id = $row->location_id;
		$post = $this->getState('request');
		if ($row->id == null) {
			$newjob = 1;
			unset ( $post ["id"] );
		} else {
			$newjob = 0;
			$old_job = getItemByFieldName ( 'ja_jobs', 'id', $row->id );
			if ($old_job)
				$old_job = $old_job [0];
		
		}
		$user = JFactory::getUser ();
		
		foreach ( $post as $k => $value ) {
			
			if ($k != 'cid' && is_array ( $value )) {				
				$post [$k] = implode ( ',', $value );
			}
			elseif ($k == 'job_detail') {
				$post [$k] = trim($value);
				// Clean text for xhtml transitional compliance
				$post [$k] = str_replace ( '<br>', '<br />', $post [$k] );
			}
			elseif(!is_array ( $value )){
				$post [$k] = trim($value);
			}
		}
		
		if (! isset ( $post ['created_date'] ) && ! isset ( $row->created_date ))
			$post ['created_date'] = date ( "Y-m-d H:i:s" );
		
		if (! $post ['user_id'])
			$post ['user_id'] = $user->id;
		if ($row->id == null)
			if (! isset ( $post ['cid'] ) || ($post ['cid'] == 0)) {
				$post ['status'] = $jbconfig ['posts']->get ( 'first_posting_status', 'Waiting' );
			} elseif (! isset ( $post ['cid'] [0] ) || ($post ['cid'] [0] == 0))
				$post ['status'] = $jbconfig ['posts']->get ( 'first_posting_status', 'Waiting' );
		
		$step = JRequest::getVar ( 'step', '' );
		
		if ($step != 'done') {
			if (! $row->bind ( $post )) {
				JError::raiseNotice ( 1, "Bind error." );
				return false;
			}
			if ($row->spec_field) {
				if (! assign_spec_field ( $controller, $row ))
					return false;
			}
			
			if ($row->editor_field)
				assign_editor_field ( $row );
			
			if (! $row->check ()) {
				return false;
			}
			
			if (! $row->store ()) {
				return false;
			} else {
				JRequest::setVar ( 'cid[]', $row->id );
				if ($newjob) {
					JRequest::setVar ( 'is_newjob', '1' );
					$this->updateAcc ( $row->is_hotjob );
					$this->checkActive ( $row );
					auto_check_jobalert_about_job ( $row, $row->cat_id, $row->location_id );
					if ($jbconfig ['emails']->get ( 'enabled' )) {
						$this->adminMailNewJob ( $row->id, $row->user_id );
					}
				} else {
					$this->saveChangeLog ( $old_job, $row );
					if (($old_location_id != $row->location_id) || ($old_cat_id != $row->cat_id) || $old_title != $row->title || $old_job_detail != $row->job_detail || $old_job_type != $row->job_type) {
						$arr_cat_id = explode ( ',', $row->cat_id );
						$old_arr_cat_id = explode ( ',', $old_cat_id );
						if ($old_cat_id != $row->cat_id)
							$diff_cat = implode ( ',', array_diff ( $arr_cat_id, $old_arr_cat_id ) );
						else {
							if ($old_location_id == $row->location_id)
								$diff_cat = '';
							else
								$diff_cat = implode ( $arr_cat_id );
						}
						if ($old_location_id != $row->location_id)
							$diff_location = $row->location_id;
						else {
							if ($diff_cat == '')
								$diff_location = '';
							else
								$diff_location = $row->location_id;
						}
						if ((($diff_cat != '') && ($diff_location != '')) || $old_title != $row->title || $old_job_detail != $row->job_detail || $old_job_type != $row->job_type)
							auto_check_jobalert_about_job ( $row, $diff_cat, $diff_location );
					}
					JRequest::setVar ( 'is_newjob', '0' );
				
				}
			}
			return true;
		}
	
		//        else {
		//            $query = "UPDATE #__ja_jobs SET is_approved = 0, posted=1 WHERE id = ".$row->id;
		//            $db->setQuery($query);   
		//            return $db->query();
		//        }
		JRequest::setVar ( 'is_newjob', $newjob );
		return true;
	}
	
	function checkActive($row) {
		$active = true;
		if (($row->effected_date > date ( 'Y-m-d H:i:s' )) || (date ( 'Y-m-d H:i:s' ) - $row->effected_date) > 30)
			$active = false;
		if ($row->status != 'Approved')
			$active = false;
		
		if ($active) {
			$db = JFactory::getDBO ();
			$query = "UPDATE #__ja_employers SET hiring=1 WHERE user_id=$row->user_id";
			$db->setQuery ( $query );
			$db->query ();
		}
	}
	
	function updateAcc($hotjob) {
		
		global $jbconfig;
		$db = JFactory::getDBO ();
		$user = JFactory::getUser ();
		$query = "SELECT * FROM #__ja_employers WHERE user_id=" . ( int ) $user->id;
		$db->setQuery ( $query );
		$employer = $db->loadObjectList ();
		if ($hotjob) {
			if ($jbconfig ['billing']->get ( 'premium_posting_fee_enabled' )) {
				$num = $employer [0]->premium_posts_balance - 1;
				$query = "UPDATE #__ja_employers SET premium_posts_balance=$num WHERE user_id=$user->id";
				$db->setQuery ( $query );
				$db->query ();
			
			}
		} else {
			if ($jbconfig ['billing']->get ( 'posting_fee_enabled' )) {
				$num = $employer [0]->standard_posts_balance - 1;
				$query = "UPDATE #__ja_employers SET standard_posts_balance=$num WHERE user_id=$user->id";
				$db->setQuery ( $query );
				$db->query ();
			}
		}
	
	}
	
	/* function activate($task){
        
        $cid = JRequest::getVar('cid', array(), 'post', 'array');
        $field = JRequest::getVar('field', "", 'post', 'cmd');
        // $table_name = JRequest::getVar('table_name',"", 'post', 'cmd');
        $table_name = 'ja_jobs';
        $n =  count($cid);
        JArrayHelper::toInteger( $cid );
        
        $active =  $task == "activate" ? 1 : 0;

        if($field == "is_starred"){
            
            $shortlistmd = JController::_createModel(JBPREFIX."ShortList", "JobBoardModel");
            $shortlistmd->starred($task == "activate" ? "starred" : "unstarred");
        } else if($table_name && $field){
            $user = &JFactory::getUser();
            if($user->id){
                $query = "UPDATE #__$table_name SET $field = $active WHERE (user_id = '".$user->id."' or '".getCurrentUserType()."' = '".JBMODERATOR_USER."') AND id = ". implode(" OR id = ", $cid);
                $db = &JFactory::getDBO();
                $db->setQuery($query);
                $db->query();

                if($table_name == "ja_jobs" && $field == "is_published"){
                    $effected = $active ? "now()" : "null";
                    $query = "UPDATE #__$table_name SET effected_date = $effected WHERE is_published = $active AND is_approved = 1 AND posted = 1 AND user_id = '".$user->id."' AND id = ". implode(" OR id = ", $cid); 
                    $db->setQuery($query); 
                    $db->query();
                }
            } else {
                 JError::raiseWarning(0, JText::_('You can not do this action'));
            }
        }
        return true;
    }        */
	
	function increaseViews($items) {
		$user = JFactory::getUser ();
		//    	$temp = $item->views + 1;
		//		$ids = explode(',',$ids);
		$id_update = array ();
		if( is_array($items) ){
			for($i = 0; $i < count ( $items ); $i ++) {			
				if ((! isset ( $_COOKIE ['viewjob_' . $items [$i]->id] )) && ((JRequest::getVar ( 'task' ) == 'multi_view') || (JRequest::getVar ( 'layout' ) == 'jaview'))){
					if ($items [$i]->user_id != $user->id && isset ( $items [$i]->views )) {
						$id_update [] = $items [$i]->id;
						setcookie ( 'viewjob_' . $items [$i]->id, 1, time () + 600 );
						$this->Set_LatestJob_View ( $items [$i] );
					}
				}
			}
		}
		$id_update = implode ( ',', $id_update );
		if ($id_update) {
			$query = "UPDATE #__ja_jobs SET views = views+1 WHERE id  IN (" . $id_update . ")";
			$db = &JFactory::getDBO ();
			$db->setQuery ( $query );
			$db->query ();
		}
	
	}
	
	function Set_LatestJob_View($item) {
		
		if (isset ( $_COOKIE ["viewjob_count"] ))
			$viewjob_count = $_COOKIE ["viewjob_count"];
		else
			$viewjob_count = 0;
		
		$viewjob_count ++;
		setcookie ( 'view_' . $viewjob_count, $item->id, time () + 60 * 60 * 2, '/' );
		setcookie ( "viewjob_count", $viewjob_count, time () + 60 * 60 * 2, '/' );
		
		$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );
	}
	
	function clear_LatestJob_View() {
		if (isset ( $_COOKIE ["viewjob_count"] )) {
			$n = $_COOKIE ["viewjob_count"];
			setcookie ( 'viewjob_count', '', time () - 3600 );
		}
		for($i = 1; $i <= $n; $i ++)
			if (isset ( $_COOKIE ['view_' . $i] ))
				setcookie ( 'view_' . $i, '' . time () - 3600 );
	}
	function getCategoryList() {
		$db = JFactory::getDBO ();
		$query = "SELECT id, name FROM #__ja_categories  WHERE (parent_id = 0 OR ISNULL(parent_id)) AND published = 1";
		$db->setQuery ( $query );
		$categories = $db->loadObjectList ();
		return $categories;
	}
	
	function check_premium_post() {
		return true;
	}
	
	function check_standard_post() {
		return true;
	}
	
	function jobMailSendFriend($job_id, $emailtemplate = 'jobMailSendFriend') {
		$user = JFactory::getUser ();
		if ($user->id == 0) {
			$user = new stdClass ( );
			$user->email = JRequest::getVar ( 'youremail' );
			$user->id = 0;
		
		}
		
		$friendemail = JRequest::getVar ( 'friendemail' );
		$subject = JRequest::getVar ( 'subject' );
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$mail_data = array ();
		$mail_data ['youremail'] = $user->email;
		$mail_data ['friendemail'] = $friendemail;
		$mail_data ['subject'] = $subject;
		$mail_data ['message'] = $message;
		
		if (! $this->checkMailData ( $mail_data ))
			return false;
		$arr_link = array ();
		$arr_link ['ja_jobs'] = $job_id;
		$arr_link ['users'] = $user->id;
		
		$arr_link ['friend_mail'] = $friendemail;
		$mail = get_EmailTemplate ( $arr_link, $emailtemplate, $message );
		
		if ($mail) {
			if ($mail_data ['youremail']) {
				$mail->EmailFromAddress = $mail_data ['youremail'];
				$mail->EmailFromName = $mail_data ['youremail'];
			}
			$result = sendMail ( $friendemail, 'My friend', $subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			return $result;
		} else {
			JError::raiseWarning ( 0, JText::_ ( 'Email template system was not found! Please contact to Administrator!!' ) );
			return false;
		}
	
	}
	
	function checkMailData($mail_data) {
		if (! $mail_data ['youremail']) {
			JError::raiseWarning ( 1, JText::_ ( 'From email address must be not empty!' ) );
			return false;
		}
		if (! $mail_data ['friendemail']) {
			JError::raiseWarning ( 1, JText::_ ( 'Receive email address must be not empty!' ) );
			return false;
		}
		if (! $mail_data ['subject']) {
			JError::raiseWarning ( 1, JText::_ ( 'Email Subject must be not empty!' ) );
			return false;
		}
		return true;
	}
	
	function jobMailSendMe($job_id, $emailtemplate = 'jobMailSendMe') {
		$user = JFactory::getUser ();
		if ($user->id == 0) {
			$user = new stdClass ( );
			$user->email = JRequest::getVar ( 'youremail' );
			$user->name = 'Guest';
		}
		$friendemail = JRequest::getVar ( 'friendemail' );
		$arr_link = array ();
		$arr_link ['ja_jobs'] = $job_id;
		$arr_link ['users'] = $user->id;
		$arr_link ['friend_mail'] = $friendemail;
		$subject = JRequest::getVar ( 'subject' );
		
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$mail = get_EmailTemplate ( $arr_link, $emailtemplate, $message );
		if ($mail) {
			sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
		}
	}
	
	/*For Administrator*/
	/**
	 * Remove field record
	 * @return Number of removed records
	 */
	function remove($task = 'remove') {
		$cid = JRequest::getVar ( 'cid' );
		if (! is_array ( $cid ))
			$cid = explode ( ',', $cid );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		$user = JFactory::getUser ();
		
		if ($n) {
			if ($task == 'remove') {
				$query = "UPDATE #__ja_applications SET job_id = null WHERE job_id IN (" . implode ( " OR id = ", $cid ) . ") and user_id=" . ( int ) $user->id;
				$query .= "; UPDATE #__ja_shortlist SET item_id = null, listtype = null WHERE listtype = 'ja_jobs' AND item_id IN (" . implode ( " OR id = ", $cid ) . ")";
				$query .= "; DELETE FROM #__ja_jobs WHERE id = " . implode ( " OR id = ", $cid );
				
				$db = &JFactory::getDBO ();
				$db->setQuery ( $query );
				return $db->queryBatch ();
			}
		}
		
		return 0;
	}
	
	function adminMailNewJob($job_id, $user_id, $email_template = 'AdminMailNewJob') {
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$user = JFactory::getUser ();
		$arr_link = array ();
		$arr_link ['ja_jobs'] = $job_id;
		$arr_link ['users'] = $user_id;
		$mail = get_EmailTemplate ( $arr_link, $email_template );
		if ($mail)
			sendMail ( $emailConfig ['admin_email'], $emailConfig ['admin_name'], $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
	}
	
	function mailEmployerNonApprovedJob($job_id, $user_id, $email_template = 'JobMailNonApproved') {
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$user = JFactory::getUser ();
		$profile = getProfileFromUserId ( $user_id );
		
		$arr_link = array ();
		$arr_link ['ja_jobs'] = $job_id;		
		$arr_link ['ja_profiles'] = $profile->id;
		$arr_link ['users'] = $user_id;
		
		$mail = get_EmailTemplate ( $arr_link, $email_template );
		if(empty($mail->EmailFromAddress))
			$mail->EmailFromAddress = $emailConfig ['admin_email'];
		if(empty($mail->EmailFromName))
			$mail->EmailFromName = $emailConfig ['admin_name'];
		if ($mail)
			sendMail( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
	}
	
	function mailEmployerUpdatedJob($job_id, $user_id, $email_template = 'sendmail_to_employer_update_job') {
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$user = JFactory::getUser ();
		$profile = getProfileFromUserId ( $user_id );
		
		$arr_link = array ();
		$arr_link ['ja_jobs'] = $job_id;		
		$arr_link ['ja_profiles'] = $profile->id;
		$arr_link ['users'] = $user_id;
		
		$mail = get_EmailTemplate ( $arr_link, $email_template );
		
		if(empty($mail->EmailFromAddress))
			$mail->EmailFromAddress = $emailConfig ['admin_email'];
		if(empty($mail->EmailFromName))
			$mail->EmailFromName = $emailConfig ['admin_name'];
		if ($mail)
			sendMail( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
	}
	
	/**
	 * Approve/Unapprove the jobs 
	 * 
	 */
	function approved($status) {
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		JArrayHelper::toInteger ( $cid );
		
		$query = "UPDATE #__ja_jobs SET status = '$status' WHERE id = " . implode ( " OR id = ", $cid );
		$db = &JFactory::getDBO ();
		$db->setQuery ( $query );
		
		return $db->query ();
	}
	
	/**
	 * Publish/Unpublish the resumes
	 * 
	 */
	function published($task = 'publish') {
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		JArrayHelper::toInteger ( $cid );
		
		$is_published = $task == 'publish' ? 1 : 0;
		
		$query = "UPDATE #__ja_resumes SET is_published = $is_published WHERE id = " . implode ( " OR id = ", $cid );
		$db = &JFactory::getDBO ();
		$db->setQuery ( $query );
		
		return $db->query ();
	}
	
	/**
	 * Checkout item
	 * 
	 */
	function checkout($uid = null) {
		$id = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $id, array (0 ) );
		
		// Make sure we have a user id to checkout the article with
		if (is_null ( $uid )) {
			$user = & JFactory::getUser ();
			$uid = $user->get ( 'id' );
		}
		
		// Lets get to it and checkout the thing...
		$item = & $this->getItem ();
		if (! $item->checkout ( $uid, $id [0] )) {
			$this->setError ( $this->_db->getErrorMsg () );
			return false;
		}
		
		return true;
	}
	
	function get_save_jobs_list() {
		$db = JFactory::getDBO ();
		$user = JFactory::getUser ();
		$sql = "select item_id from #__ja_shortlist where user_id=" . ( int ) $user->id . " and listtype='ja_jobs'";
		$db->setQuery ( $sql );
		$result = $db->loadResultArray ();
		$items_id = '';
		if ($result) {
			$items_id = implode ( ',', $result );
		}
		return $items_id;
	}
	
	function check_jobsendmail_jobseeker($job_id) {
		$obj_object = getItemByFieldName ( 'ja_jobs', 'id', $job_id );
		$obj_object = $obj_object [0];
	
	}
	
	
	function show_result_jobalert() {
		global $option, $jbconfig;
		$db = JFactory::getDBO ();
		$limitstart = JRequest::getInt ( 'limitstart', 0 );
		$limit = JRequest::getInt ( 'limit', $jbconfig ['posts']->get ( 'display_num' ) );
		$jobalert_id = JRequest::getVar ( 'cid' );
		$jobalert_id = $jobalert_id [0];
		$query = "SELECT * FROM #__ja_jobalerts WHERE id=" . ( int ) $jobalert_id;
		$db->setQuery ( $query );
		$jobalert_result = $db->loadObject ();	
		
		// Job Alert result
		if ($jobalert_result->category) {
			$query = "SELECT * FROM #__ja_categories WHERE id IN ($jobalert_result->category)";
			$db->setQuery ( $query );
			$result = $db->loadObjectList ();
			$arr_category = array ();
			if (is_array ( $result ))
				foreach ( $result as $category )
					$arr_category [] = $category->name;
			JRequest::setVar ( 'cat_id', implode ( ',', $arr_category ) );
		}
		
		if ($jobalert_result->location) {
			$query = "SELECT * FROM #__ja_location WHERE id IN ($jobalert_result->location)";
			$db->setQuery ( $query );
			$result = $db->loadObjectList ();
			$arr_location = array ();
			if (is_array ( $result ))
				foreach ( $result as $location )
					$arr_location [] = $location->name;
			
			JRequest::setVar ( 'location_id', implode ( ',', $arr_location ) );
		}
		if ($jobalert_result->job_type) {
			$query = "SELECT * FROM #__ja_codes WHERE value = '$jobalert_result->job_type' AND field_id='ja_jobs_job_type'";
			$db->setQuery ( $query );
			$result = $db->loadObject ();
			JRequest::setVar ( 'job_type', $result->text );
			//			JRequest::setVar('job_type_name',$result->text);
		}
		if ($jobalert_result->keyword) {
			if ($jobalert_result->keyword_option == '3')
				JRequest::setVar ( 'filter_keyword', '"' . $jobalert_result->keyword . '"' );
			else
				JRequest::setVar ( 'filter_keyword', $jobalert_result->keyword );
		}
		if ($jobalert_result->posted_date)
		{
			JRequest::setVar ( 'posted_date', $jobalert_result->posted_date );
			JRequest::setVar('is_jobfilter',1);
		}
		
		if ($jobalert_result->job_author)
		{
			JRequest::setVar ( 'job_author', $jobalert_result->job_author );
			JRequest::setVar('is_jobfilter',1);
		}
			//		if ($jobalert_result->job_distance)
		//		{
		//			$query = "SELECT * FROM #__ja_codes WHERE value IN ($jobalert_result->job_distance) AND field_id='ja_jobs_distance'";
		//			$db->setQuery($query);
		//			$result = $db->loadObjectList();
		//			$arr_distance = array();
		//			if (is_array($result))
		//				foreach ($result as $distance)
		//					$arr_distance[] = $distance->text;
		//			JRequest::setVar('distance',implode(',',$arr_distance));
		//			
		//		}
		JRequest::setVar ( 'jobalert', 1 );
		return $this->search_job ();		
	}
	
	function search_job() {
		global $option, $jbconfig, $mainframe;
		$db =& JFactory::getDBO ();
		/* Get items list */
		$limitstart = JRequest::getInt('limitstart', 0);
		$limit		= $mainframe->getUserStateFromRequest( $option.'.jajobs.limit',		'limit',	$jbconfig['posts']->get('display_num', 20),	'int' );
		$where_more = '';
		$where_more .= ' and a.status=\'Approved\' ';
		$where_more .= ' AND ( a.expiry_date >= now() OR a.expiry_date is NULL ) and(a.effected_date<=now()) and ( (DATE_ADD(a.effected_date, INTERVAL ' . ( int ) $jbconfig ['posts']->get ( 'posts_display_days', 30 ) . ' DAY) >= now()  AND a.is_hotjob=0) or (DATE_ADD(a.effected_date, INTERVAL ' . ( int ) $jbconfig ['posts']->get ( 'posts_show_days_elapsed', 30 ) . ' DAY) >= now()  AND a.is_hotjob=1) )';
		
		//Filter Job author for job alert
		$job_author = JRequest::getVar ( 'job_author' );
		if ($job_author){
			$where_more .= ' and (a.user_id IN (' . $job_author . '))';
		}
		
		$arr_jobsearch_keyword = '';
		$jobsearch_keyword = JRequest::getVar ( 'filter_keyword', '')?JRequest::getVar ( 'filter_keyword' ):JRequest::getVar ( 'keyword' );
		JRequest::setVar('filter_keyword', $jobsearch_keyword);		
		if ($jobsearch_keyword != JText::_ ( 'Enter keyword...' ) && $jobsearch_keyword != '') {
			JRequest::setVar ( 'search', $jobsearch_keyword );
			JRequest::setVar ( 'is_jobfilter', 1 );
			$arr_jobsearch_keyword = standardize_keyword ( $jobsearch_keyword );
			setcookie ( 'cookie_filter_keyword', $jobsearch_keyword, time () + 3600 );
		}
		
		
		/* Special for Salary */
		
		$search_job = array();
		
		//Checking minimum salary field activation
		$filter_salary_from = JRequest::getInt ( 'filter_salary_from', 0 );
		$filter_salary_to 	= JRequest::getInt ( 'filter_salary_to', 0 );
		
		if($filter_salary_from && check_field_exist('salary_min', 'ja_jobs') ){
			$search_job ['salary_min'] = $filter_salary_from;
		}
		if($filter_salary_to && check_field_exist('salary_max', 'ja_jobs') ){
			$search_job ['salary_max'] = $filter_salary_to;
		}	
		
		if (count ( $search_job ) > 0) {
			if (isset ( $search_job ['salary_min'] )) {
				$where_more .= ' and a.salary_min>='.(int)$search_job ['salary_min'] ;				
			}
			if (isset ( $search_job ['salary_max'] )) {
				$where_more .= ' and a.salary_max<='.(int)$search_job ['salary_max'] ;				
			}			
			JRequest::setVar ( 'is_jobfilter', 1 );
		}
		
		$items = $this->getItems ( $where_more, $limit, $limitstart );
		
		$filter_list = array ();
		if ($items) {
			$search_job = array ();
			$uri = JURI::getInstance ();
			$request = $uri->getQuery ( true );			
			
			$theme = JRequest::getVar('theme');
			if (!$theme)	$theme = $jbconfig['general']->get('theme', 'default');			
		    
			// Implement zipcode distance search.
			$zipcode_from = JRequest::getVar("zipcode_from", "");
			$zipcode_distance = JRequest::getVar("zipcode_distance", "");			
			if( $zipcode_from != "" && $zipcode_distance != "" ){
			    global $jbconfig;
			    $zip_field_name = "zipcode";
			    $zip_reference_table = "";
				
				$result = $this->getFilterField();				
				if($result){
			        $zip_reference_table = $result->referred_table;
				}
			    
			    // Get lat, long of From Zipcode
		        $query = "SELECT latitude, longitude FROM #__".$zip_reference_table." WHERE zipcode = ".$zipcode_from;
		        $db->setQuery($query);
		        $resultFrom = $db->loadObject();		        
		    }
			
			foreach ( $items as $i => $job ) {
				
				if ($jobsearch_keyword != JText::_ ( 'Enter keyword...' ) && $jobsearch_keyword != '' && ! JRequest::getVar ( 'module_recent_viewed_job' ) && $theme=='default') {
					$job->alias = JFilterOutput::stringURLSafe ( trim ( $job->title ) );
					foreach ( $arr_jobsearch_keyword as $k => $value ) {
						$temp = stripos ( $job->title, $value );
						if (is_numeric ( $temp )) {
							$temp = substr ( $job->title, $temp, strlen ( $value ) );
							$job->title = str_ireplace ( $value, "<strong class='highlight'>" . $temp . "</strong>", $job->title );
						}
						$temp = stripos ( $job->job_detail, $value );
						if (is_numeric ( $temp )) {
							$temp = substr ( $job->job_detail, $temp, strlen ( $value ) );
							$job->job_detail = str_ireplace ( $value, "<strong class='highlight'>" . $temp . "</strong>", $job->job_detail );
						}
					}				
				}
				
				if( isset($zip_field_name) && isset($zip_reference_table) ){				    
				    if( isset($job->{$zip_field_name}) ){				        
				        $query = "SELECT latitude, longitude FROM #__".$zip_reference_table." WHERE zipcode = ".$job->{$zip_field_name};				        
        		        $db->setQuery($query);
        		        $resultTo = $db->loadObject();        		        
        		        if( $resultFrom && $resultTo ){
        		            $distance = $this->calcDist($resultFrom->latitude, $resultFrom->longitude, $resultTo->latitude, $resultTo->longitude);
        		            
        		            if( $distance > $zipcode_distance ){
        		              unset($items[$i]);
        		            }else {
        		                $job->zipcode_distance = $distance;        		                
				            }
        		        }else unset($items[$i]);
				    }else unset($items[$i]);
				}
			}
		}
		
		if( isset($zip_field_name) && isset($zip_reference_table) ){
    		$arr = array();
    		foreach ( $items as $i => $job ) {
    		 if( isset($items[$i]) )   
    		  $arr[] = $items[$i];
    		}
    		$items = $arr;
		}
		
		return $items;
	}
	
	function calcDist($lat_A, $long_A, $lat_B, $long_B) {

      $distance = sin(deg2rad($lat_A))
                    * sin(deg2rad($lat_B))
                    + cos(deg2rad($lat_A))
                    * cos(deg2rad($lat_B))
                    * cos(deg2rad($long_A - $long_B));
    
      $distance = (rad2deg(acos($distance))) * 69.09;
    
      return number_format( $distance, 2, ".", ",");
    } 
	
	function remove_attach() {
		remove_attach ( 'ja_jobs' );
	
	}
	
	function getItemNotes($items) {
		$temp = array ();
		for($i = 0; $i < count ( $items ); $i ++)
		if (isset($items[$i]->id))
			$temp [] = $items [$i]->id;
		$item_list = implode ( ',', $temp );
		if ($item_list) {
			$where = " and item_id IN ($item_list) and note_type='ja_jobs'";
			$note_list = getItemNotes ( $where );
			
			return $note_list;
		}
		return '';
	}
	
	function geItemView_List() {
		$cid = JRequest::getVar ( 'cid' );
		$db = JFactory::getDBO ();
		if (count ( $cid ) > 0) {
			if (JRequest::getVar ( 'pre_layout', 'jaview' ) == 'jalist') {
				$limit = 5;
				$limitstart = 0;
			} else {
				$limit = JRequest::getVar ( 'limit', 5 );
				$limitstart = JRequest::getVar ( 'limitstart', 0 );
			
			}
			
			if (is_array ( $cid ))	$str_cid = implode ( ',', $cid );
			else	$str_cid = $cid;
			
			$query = "SELECT * FROM #__ja_jobs WHERE id IN ($str_cid) ORDER BY effected_date DESC LIMIT $limitstart , $limit";
			$db->setQuery ( $query );
			$item_views = $db->loadObjectList ();
			$this->increaseViews ( $item_views );
			jimport ( 'joomla.html.pagination' );
			require_once (JPATH_COMPONENT_SITE . DS . 'helper' . DS . 'japagination.php');
			
			$this->_pagination = new JAPagination ( count ( explode ( ',', $str_cid ) ), $limitstart, $limit );
			
			return $item_views;
		} else
			return '';
	}
	
	function getAppForItemView($where) {
		$db = JFactory::getDBO ();
		$query = "SELECT id,job_id FROM #__ja_applications WHERE 1=1  $where";
		$db->setQuery ( $query );
		$result = $db->loadObjectList ();
		if (count ( $result ) > 0) {
			$app_list = array ();
			foreach ( $result as $application ) {
				$app_list [$application->job_id] = $application->id;
			}
			return $app_list;
		} else
			return '';
	}
	function getProfileForItemView($arr_profile) {
		
		$db = JFactory::getDBO ();
		foreach ( $arr_profile as $key => $value ) {
			$query = "SELECT * FROM #__ja_profiles WHERE  user_id=" . ( int ) $value;
			$db->setQuery ( $query );
			$result = $db->loadObject ();
			$arr_profile [$key] = $result;
		}
		return $arr_profile;
	}
	function getNoteForItemView($where) {
		$db = JFactory::getDBO ();
		$query = "SELECT * FROM #__ja_notes WHERE 1=1  $where";
		$db->setQuery ( $query );
		$result = $db->loadObjectList ();
		if (count ( $result ) > 0) {
			$note_list = array ();
			foreach ( $result as $note ) {
				$note_list [$note->item_id] = $note;
			}
			return $note_list;
		} else
			return '';
	}
	
	function getSuggestURL() {
		$db = JFactory::getDBO ();
		$user = JFactory::getUser ();
		$query = "SELECT direct_url FROM #__ja_jobs WHERE user_id=" . ( int ) $user->id . " ORDER BY created_date";
		$db->setQuery ( $query );
		$result = $db->loadObjectList ();
		$temp = array ();
		for($i = 0; $i < count ( $result ); $i ++)
			if (! in_array ( $result [$i]->direct_url, $temp ))
				$temp [] = $result [$i]->direct_url;
		$result = array ();
		for($i = 0; $i < count ( $temp ); $i ++) {
			$url = new stdClass ( );
			$url->direct_url = $temp [$i];
			$result [] = $url;
		}
		
		return $result;
	}
	
	function saveChangeLog($old_job, $new_job) {
		global $jbconfig;
		$fieldlist = $this->getEditFieldList ();
		$change_log = '';
		for($i = 0; $i < count ( $fieldlist ); $i ++)
			if ($old_job->{$fieldlist [$i]->field_name} != $new_job->{$fieldlist [$i]->field_name}) {
				$change_log .= '<br />' . JText::_ ( $fieldlist [$i]->label ) . ":" . rendfield ( $new_job, $fieldlist [$i], false, true, true );
			}
		if ($change_log != '') {
			$change_log = JText::_ ( 'Updated date' ) . ':' . date ( 'Y-m-d H:i:s' ) . '<br />' . JText::_ ( 'Job ID' ) . ':' . $new_job->id . '<br />' . $change_log . '<br />-------------------------------------------------------------------------<br />';
			$db = JFactory::getDBO ();
			$query = "SELECT * FROM #__ja_profiles WHERE modified_notice=1 and user_id=" . $new_job->user_id;
			$db->setQuery ( $query );
			$result = $db->loadObject ();
			if ($result) {
				$change_log = $result->change_log . '<br />' . $change_log;
				$query = "UPDATE #__ja_profiles SET change_log='" . $change_log . "' WHERE user_id=" . $result->user_id;
				$db->setQuery ( $query );
				$db->query ();
			}
		}
	}
	
	function show_result_searchform() {
		
		global $option, $jbconfig;
		$db = JFactory::getDBO ();
		$limitstart = JRequest::getInt ( 'limitstart', 0 );
		$limit = JRequest::getInt ( 'limit', $jbconfig ['posts']->get ( 'display_num' ) );
		//Category filter
		$category = JRequest::getVar ( 'category' );
		if (is_array ( $category ))
			$category = implode ( ',', $category );
		if ($category) {
			$query = "SELECT * FROM #__ja_categories WHERE id IN ($category)";
			$db->setQuery ( $query );
			$result = $db->loadObjectList ();
			$arr_category = array ();
			if (is_array ( $result ))
				foreach ( $result as $category )
					$arr_category [] = $category->name;
			JRequest::setVar ( 'cat_id', implode ( ',', $arr_category ) );
		}
		
		//Location filter
		$location = JRequest::getVar ( 'location' );
		
		if ($location) {
			$query = "SELECT * FROM #__ja_location WHERE id IN ($location)";
			$db->setQuery ( $query );
			$result = $db->loadObjectList ();
			$arr_location = array ();
			if (is_array ( $result ))
				foreach ( $result as $location )
					$arr_location [] = $location->name;
			
			JRequest::setVar ( 'location_id', implode ( ',', $arr_location ) );
		}
		$job_type = JRequest::getVar ( 'job_type' );
		if ($job_type) {
			$query = "SELECT * FROM #__ja_codes WHERE value = '$job_type' AND field_id='ja_jobs_job_type'";
			$db->setQuery ( $query );
			$result = $db->loadObject ();
			JRequest::setVar ( 'job_type', $result->text );
			//			JRequest::setVar('job_type_name',$result->text);
		}
		$keyword = JRequest::getVar ( 'keyword' );
		$keyword_option = JRequest::getVar ( 'keyword_option' );
		if ($keyword) {
			if ($keyword_option == '3')
				JRequest::setVar ( 'filter_keyword', '"' . $keyword . '"' );
			else
				JRequest::setVar ( 'filter_keyword', $keyword );
		}
		//		$posted_date = JRequest::getVar('posted_date');
		//		if ($posted_date)
		//			JRequest::setVar('posted_date',$jobalert_result->posted_date);
		//			
		//		if ($jobalert_result->job_author)
		//			JRequest::setVar('job_author',$jobalert_result->job_author);
		//		$job_distance = JRequest::getVar('job_distance');
		//		if (is_array($job_distance))
		//		{
		//			for ($i=0;$i<count($job_distance);$i++)
		//				$job_distance[$i] = "'".$job_distance[$i]."'";
		//			$job_distance = implode(',',$job_distance);
		//		}
		//		
		//		if ($job_distance)
		//		{
		//			$query = "SELECT * FROM #__ja_codes WHERE value IN ($job_distance) AND field_id='ja_jobs_distance'";
		//			$db->setQuery($query);
		//			$result = $db->loadObjectList();
		//			
		//			$arr_distance = array();
		//			if (is_array($result))
		//				foreach ($result as $distance)
		//					$arr_distance[] = $distance->text;
		//			JRequest::setVar('distance',implode(',',$arr_distance));
		//			
		//		}		
		

		JRequest::setVar ( 'jobalert', 1 );
		$items = $this->search_job ();
		$initial_total = JRequest::getVar ( 'initial_total' );
		$total = count ( $items );
		$temp_items = array ();
		for($i = 0; $i < $initial_total; $i ++) {
			if (isset ( $items [$i] ))
				$temp_items [] = $items [$i];
		}
		$items = $temp_items;
		//		require_once(JPATH_COMPONENT_SITE.'/helper/japagination.php');
		$this->_pagination = new JPagination ( $total, $limitstart, $limit );
		if (is_array ( $items ))
			$items = array_slice ( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		return $items;
	}
	function buildJobId_JS($job_id)
	{
		echo '<script language="javascript" type="text/javascript">';
		echo '/* <![CDATA[ */';
		
		if (is_array($job_id))
		{
			echo 'var num_job='.count($job_id).';';
			echo 'var arr_job_id = new Array(num_job);';
			foreach ($job_id as $id)
			{
				echo 'arr_job_id[]='.$id.';';
			}
		}
		else 
		{
			echo 'var num_job=1;';
			echo 'var arr_job_id = new Array('.$job_id.');';
		}
		echo '/* ]]> */';
		echo '</script>';
	}
	
	function getNumApplications( $jobID ){
	    if( !empty($jobID) ){
	       global $option, $jbconfig;
	       $db = JFactory::getDBO ();
           
	       $query = "SELECT count(id) FROM #__ja_applications WHERE job_id = '{$jobID}' AND ( params NOT LIKE '%employer_removed%' OR params IS NULL)";
	       $db->setQuery ( $query );
	       return $db->loadResult();
	    }
        
        return "0";
	}
	
	function getFilterField(){
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT * FROM #__ja_form_fields WHERE field_name='zipcode' AND table_name='ja_jobs' AND is_on_filter = 1 AND is_referred = 1 AND referred_key <> '' AND referred_value <> '' AND referred_table <> '' ");
		$result = $db->loadObject();
		return $result;
	}
}
?>